import Mock from 'mockjs'
import { param2Obj, randomNum, randomItem, deepClone } from '../utils'

const Random = Mock.Random

/**
 * 生成物资类别数据
 */
const materialCategories = [
  { id: '1', name: '药品' },
  { id: '2', name: '医疗器械' },
  { id: '3', name: '办公用品' },
  { id: '4', name: '耗材' },
  { id: '5', name: '防护用品' }
]

/**
 * 生成物资列表数据
 */
const generateMaterialList = (query) => {
  const category = query.category
  const total = 35
  const pageSize = parseInt(query.pageSize) || 10
  const currentPage = parseInt(query.currentPage) || 1
  
  const list = []
  for (let i = 0; i < pageSize; i++) {
    const id = 'MAT' + (10000 + i + (currentPage - 1) * pageSize).toString()
    if ((currentPage - 1) * pageSize + i < total) {
      const categoryId = category || Random.pick(materialCategories.map(c => c.id))
      list.push({
        id,
        name: Random.ctitle(4, 8),
        code: 'M' + Random.string('number', 6),
        category: categoryId,
        categoryName: materialCategories.find(c => c.id === categoryId).name,
        specification: Random.pick(['小型', '中型', '大型']),
        unit: Random.pick(['盒', '瓶', '台', '个', '包']),
        stock: Random.integer(0, 100),
        price: Random.float(10, 5000, 2, 2),
        supplier: Random.cword(4, 8) + Random.pick(['医疗', '科技', '生物', '制药']) + '公司',
        expireDate: Random.date('yyyy-MM-dd'),
        status: Random.pick(['normal', 'low', 'out'])
      })
    }
  }
  
  return {
    code: 200,
    message: 'success',
    data: {
      list,
      categories: materialCategories,
      pagination: {
        total,
        pageSize,
        currentPage
      }
    }
  }
}

/**
 * 生成物资详情数据
 */
const generateMaterialDetail = (id) => {
  const categoryId = Random.pick(materialCategories.map(c => c.id))
  
  return {
    code: 200,
    message: 'success',
    data: {
      id,
      name: Random.ctitle(4, 8),
      code: 'M' + Random.string('number', 6),
      category: categoryId,
      categoryName: materialCategories.find(c => c.id === categoryId).name,
      specification: Random.pick(['小型', '中型', '大型']),
      unit: Random.pick(['盒', '瓶', '台', '个', '包']),
      stock: Random.integer(0, 100),
      price: Random.float(10, 5000, 2, 2),
      supplier: Random.cword(4, 8) + Random.pick(['医疗', '科技', '生物', '制药']) + '公司',
      produceDate: Random.date('yyyy-MM-dd'),
      expireDate: Random.date('yyyy-MM-dd'),
      storageCondition: Random.pick(['常温', '冷藏', '冷冻', '避光']),
      status: Random.pick(['normal', 'low', 'out']),
      description: Random.cparagraph(1, 3),
      history: (() => {
        const history = []
        const count = Random.integer(0, 5)
        for (let i = 0; i < count; i++) {
          history.push({
            date: Random.date('yyyy-MM-dd'),
            type: Random.pick(['in', 'out']),
            quantity: Random.integer(1, 20),
            operator: Random.cname(),
            remark: Random.csentence(5, 15)
          })
        }
        return history
      })()
    }
  }
}

/**
 * 生成物资统计数据
 */
const generateMaterialStats = () => {
  return {
    code: 200,
    message: 'success',
    data: {
      stockCount: Random.integer(50, 200),
      lowStock: Random.integer(0, 10),
      categories: materialCategories.length
    }
  }
}

/**
 * 设置物资模块Mock
 */
export function setupMaterialMock() {
  // 获取物资列表
  Mock.mock(/\/api\/material\/list/, 'get', (options) => {
    const url = options.url
    const query = {}
    url.replace(/\?(.+)/, function(_, search) {
      search.split('&').forEach(function(item) {
        const parts = item.split('=')
        query[parts[0]] = parts[1]
      })
    })
    return generateMaterialList(query)
  })
  
  // 获取物资详情
  Mock.mock(/\/api\/material\/detail\/\w+/, 'get', (options) => {
    const id = options.url.match(/\/api\/material\/detail\/(\w+)/)[1]
    return generateMaterialDetail(id)
  })
  
  // 提交物资申领
  Mock.mock('/api/material/apply', 'post', () => {
    return {
      code: 200,
      message: 'success',
      data: {
        id: 'REQ' + Random.integer(10000, 99999),
        status: 'pending'
      }
    }
  })
  
  // 获取物资统计
  Mock.mock('/api/material/stats', 'get', generateMaterialStats)
  
  // 获取入库数据
  Mock.mock('/api/material/inbound', 'post', (options) => {
    return {
      code: 200,
      message: 'success',
      data: {
        id: 'IN' + Random.integer(10000, 99999),
        materialId: JSON.parse(options.body).materialId,
        quantity: JSON.parse(options.body).quantity,
        newStock: Random.integer(50, 200),
        operator: Random.cname(),
        createTime: new Date().toISOString()
      }
    }
  })
  
  // 获取出库数据
  Mock.mock('/api/material/outbound', 'post', (options) => {
    return {
      code: 200,
      message: 'success',
      data: {
        id: 'OUT' + Random.integer(10000, 99999),
        materialId: JSON.parse(options.body).materialId,
        quantity: JSON.parse(options.body).quantity,
        newStock: Random.integer(10, 100),
        operator: Random.cname(),
        createTime: new Date().toISOString()
      }
    }
  })
  
  // 获取库存预警列表
  Mock.mock(/\/api\/material\/warning\/list/, 'get', (options) => {
    const url = options.url
    const query = {}
    url.replace(/\?(.+)/, function(_, search) {
      search.split('&').forEach(function(item) {
        const parts = item.split('=')
        query[parts[0]] = parts[1]
      })
    })
    
    const list = []
    for (let i = 0; i < 15; i++) {
      list.push({
        id: i + 1,
        name: Random.ctitle(4, 8),
        code: 'M' + Random.string('number', 6),
        category: Random.pick(['办公用品', '电子设备', '生活用品', '医疗用品']),
        specification: Random.pick(['小型', '中型', '大型']),
        unit: Random.pick(['盒', '瓶', '台', '个', '包']),
        stock: Random.integer(0, 9),
        warningStock: 10,
        price: Random.float(10, 5000, 2, 2),
        supplier: Random.cword(4, 8) + Random.pick(['医疗', '科技', '生物', '制药']) + '公司'
      })
    }
    
    return {
      code: 200,
      message: 'success',
      data: {
        list,
        total: 15,
        page: parseInt(query.page || 1),
        pageSize: parseInt(query.pageSize || 10)
      }
    }
  })
  
  // 更新预警设置
  Mock.mock('/api/material/warning/settings', 'put', (options) => {
    return {
      code: 200,
      message: 'success',
      data: JSON.parse(options.body)
    }
  })
  
  // 获取物资报表数据
  Mock.mock(/\/api\/material\/report/, 'get', (options) => {
    const url = options.url
    const query = {}
    url.replace(/\?(.+)/, function(_, search) {
      search.split('&').forEach(function(item) {
        const parts = item.split('=')
        query[parts[0]] = parts[1]
      })
    })
    
    return {
      code: 200,
      data: {
        statistics: {
          totalInbound: Random.integer(500, 2000),
          totalOutbound: Random.integer(300, 1500),
          totalTypes: Random.integer(30, 100),
          activeUsers: Random.integer(10, 50)
        },
        rankings: {
          inbound: [
            { name: '口罩', value: Random.integer(100, 500) },
            { name: '消毒液', value: Random.integer(80, 300) },
            { name: '手套', value: Random.integer(50, 200) },
            { name: '药品', value: Random.integer(40, 150) },
            { name: '防护服', value: Random.integer(30, 120) }
          ],
          outbound: [
            { name: '口罩', value: Random.integer(90, 400) },
            { name: '消毒液', value: Random.integer(70, 250) },
            { name: '手套', value: Random.integer(40, 180) },
            { name: '药品', value: Random.integer(30, 130) },
            { name: '防护服', value: Random.integer(20, 100) }
          ]
        },
        trend: {
          dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
          inbound: [120, 132, 101, 134, 90, 180],
          outbound: [90, 110, 90, 120, 80, 160]
        },
        category: [
          { name: '办公用品', value: 35 },
          { name: '电子设备', value: 20 },
          { name: '医疗用品', value: 25 },
          { name: '清洁用品', value: 10 },
          { name: '其他', value: 10 }
        ]
      },
      message: '获取报表数据成功'
    }
  })
}

// 物资分类
const categories = [
  { id: 1, name: '办公用品', icon: 'bookmark-o' },
  { id: 2, name: '电子设备', icon: 'phone-o' },
  { id: 3, name: '生活用品', icon: 'shopping-cart-o' },
  { id: 4, name: '实验材料', icon: 'gem-o' },
  { id: 5, name: '维修工具', icon: 'tools-o' }
]

// 部门列表
const departments = [
  '人力资源部',
  '财务部',
  '研发部',
  '市场部',
  '销售部',
  '客服部',
  '行政部',
  '法务部'
]

// 生成物资数据
function generateMaterials() {
  const items = []
  const count = 86
  
  for (let i = 0; i < count; i++) {
    const id = i + 1
    const category = randomItem(categories)
    const images = []
    const imageCount = randomNum(1, 4)
    
    for (let j = 0; j < imageCount; j++) {
      images.push(Random.image('400x400', Random.color(), '#FFF', 'Material'))
    }
    
    const attributes = []
    const attrCount = randomNum(3, 8)
    for (let j = 0; j < attrCount; j++) {
      attributes.push({
        name: Random.word(4, 8),
        value: Random.word(3, 10)
      })
    }
    
    items.push({
      id,
      title: Random.ctitle(5, 15),
      images,
      price: Random.float(10, 10000, 2, 2),
      stock: Random.integer(0, 1000),
      unit: randomItem(['个', '台', '套', '箱', '包', '件']),
      category: category.id,
      categoryName: category.name,
      description: Random.cparagraph(5, 10),
      attributes,
      supplier: Random.cname() + Random.ctitle(2, 4) + '公司',
      warrantyPeriod: randomItem(['无', '1个月', '3个月', '6个月', '1年', '2年', '3年', '5年', '终身']),
      createTime: Random.date('yyyy-MM-dd HH:mm:ss'),
      updateTime: Random.date('yyyy-MM-dd HH:mm:ss'),
      tags: Array.from({ length: randomNum(1, 3) }, () => Random.ctitle(2, 4)),
      isFavorite: Random.boolean(),
      views: Random.integer(0, 10000),
      applicationCount: Random.integer(0, 500)
    })
  }
  
  return items
}

// 生成申请记录
function generateApplyRecords(materialId) {
  const count = randomNum(0, 15)
  const records = []
  
  for (let i = 0; i < count; i++) {
    records.push({
      id: Random.guid(),
      materialId,
      applicant: Random.cname(),
      department: randomItem(departments),
      quantity: Random.integer(1, 20),
      reason: Random.cparagraph(1, 3),
      status: randomItem(['审批中', '已通过', '已拒绝', '已领取']),
      applyTime: Random.date('yyyy-MM-dd HH:mm:ss'),
      approveTime: Random.date('yyyy-MM-dd HH:mm:ss')
    })
  }
  
  return records.sort((a, b) => new Date(b.applyTime) - new Date(a.applyTime))
}

// 所有物资数据
const materialsList = generateMaterials()

// 用户收藏的物资IDs
let favoriteMaterialIds = Array.from({ length: randomNum(5, 15) }, () => 
  randomItem(materialsList).id
)

// 获取物资列表
function getMaterials(config) {
  const { keyword, category, sort, page = 1, pageSize = 10 } = param2Obj(config.url)
  
  let filteredList = [...materialsList]
  
  // 关键词搜索
  if (keyword) {
    const kw = keyword.toLowerCase()
    filteredList = filteredList.filter(item => 
      item.title.toLowerCase().includes(kw) || 
      item.description.toLowerCase().includes(kw) || 
      item.supplier.toLowerCase().includes(kw)
    )
  }
  
  // 分类筛选
  if (category) {
    filteredList = filteredList.filter(item => item.category == category)
  }
  
  // 排序
  if (sort) {
    const [field, order] = sort.split(':')
    filteredList.sort((a, b) => {
      let result = 0
      if (field === 'price') {
        result = a.price - b.price
      } else if (field === 'createTime') {
        result = new Date(a.createTime) - new Date(b.createTime)
      } else if (field === 'views') {
        result = a.views - b.views
      } else if (field === 'applicationCount') {
        result = a.applicationCount - b.applicationCount
      }
      
      return order === 'desc' ? -result : result
    })
  }
  
  // 分页
  const start = (page - 1) * pageSize
  const end = start + parseInt(pageSize)
  const pageList = filteredList.slice(start, end)
  
  return {
    code: 200,
    data: {
      total: filteredList.length,
      list: pageList,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    },
    message: '获取物资列表成功'
  }
}

// 获取物资详情
function getMaterialDetail(config) {
  const id = config.url.match(/\/api\/materials\/(\d+)/)[1]
  const material = materialsList.find(item => item.id == id)
  
  if (!material) {
    return {
      code: 404,
      message: '物资不存在'
    }
  }
  
  // 更新物资是否被收藏
  material.isFavorite = favoriteMaterialIds.includes(material.id)
  
  return {
    code: 200,
    data: material,
    message: '获取物资详情成功'
  }
}

// 获取物资分类
function getMaterialCategories() {
  return {
    code: 200,
    data: categories,
    message: '获取物资分类成功'
  }
}

// 申请物资
function applyMaterial(config) {
  const { materialId, quantity, reason, department } = JSON.parse(config.body)
  
  // 验证物资是否存在
  const material = materialsList.find(item => item.id == materialId)
  if (!material) {
    return {
      code: 404,
      message: '物资不存在'
    }
  }
  
  // 验证库存是否充足
  if (material.stock < quantity) {
    return {
      code: 400,
      message: '库存不足'
    }
  }
  
  // 创建申请记录
  const record = {
    id: Random.guid(),
    materialId,
    applicant: '当前用户',
    department,
    quantity,
    reason,
    status: '审批中',
    applyTime: new Date().toISOString().replace('T', ' ').slice(0, 19)
  }
  
  // 更新物资申请次数
  material.applicationCount += 1
  
  return {
    code: 200,
    data: record,
    message: '申请提交成功，等待审批'
  }
}

// 收藏/取消收藏物资
function toggleFavoriteMaterial(config) {
  const id = config.url.match(/\/api\/materials\/(\d+)\/favorite/)[1]
  const { isFavorite } = JSON.parse(config.body)
  
  // 验证物资是否存在
  const material = materialsList.find(item => item.id == id)
  if (!material) {
    return {
      code: 404,
      message: '物资不存在'
    }
  }
  
  if (isFavorite) {
    // 添加到收藏
    if (!favoriteMaterialIds.includes(material.id)) {
      favoriteMaterialIds.push(material.id)
    }
  } else {
    // 从收藏中移除
    favoriteMaterialIds = favoriteMaterialIds.filter(item => item !== material.id)
  }
  
  // 更新物资收藏状态
  material.isFavorite = isFavorite
  
  return {
    code: 200,
    data: { isFavorite },
    message: isFavorite ? '收藏成功' : '已取消收藏'
  }
}

// 获取相关物资
function getRelatedMaterials(config) {
  const id = config.url.match(/\/api\/materials\/(\d+)\/related/)[1]
  const { limit = 4 } = param2Obj(config.url)
  
  // 验证物资是否存在
  const material = materialsList.find(item => item.id == id)
  if (!material) {
    return {
      code: 404,
      message: '物资不存在'
    }
  }
  
  // 从同类物资中随机选择几个作为相关物资
  const sameCategoryMaterials = materialsList.filter(item => 
    item.category === material.category && item.id !== material.id
  )
  
  let relatedItems = []
  if (sameCategoryMaterials.length > 0) {
    // 随机选择指定数量的相关物资
    const count = Math.min(parseInt(limit), sameCategoryMaterials.length)
    const shuffled = [...sameCategoryMaterials].sort(() => 0.5 - Math.random())
    relatedItems = shuffled.slice(0, count)
  }
  
  return {
    code: 200,
    data: relatedItems,
    message: '获取相关物资成功'
  }
}

// 获取物资申请记录
function getMaterialApplyRecords(config) {
  const id = config.url.match(/\/api\/materials\/(\d+)\/apply-records/)[1]
  const { page = 1, pageSize = 10 } = param2Obj(config.url)
  
  // 验证物资是否存在
  const material = materialsList.find(item => item.id == id)
  if (!material) {
    return {
      code: 404,
      message: '物资不存在'
    }
  }
  
  // 获取申请记录
  const records = generateApplyRecords(material.id)
  
  // 分页
  const start = (page - 1) * pageSize
  const end = start + parseInt(pageSize)
  const pageList = records.slice(start, end)
  
  return {
    code: 200,
    data: {
      total: records.length,
      list: pageList,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    },
    message: '获取物资申请记录成功'
  }
}

// 获取收藏物资列表
function getFavoriteMaterials(config) {
  const { page = 1, pageSize = 10 } = param2Obj(config.url)
  
  const favoriteList = materialsList.filter(item => 
    favoriteMaterialIds.includes(item.id)
  )
  
  // 分页
  const start = (page - 1) * pageSize
  const end = start + parseInt(pageSize)
  const pageList = favoriteList.slice(start, end)
  
  return {
    code: 200,
    data: {
      total: favoriteList.length,
      list: pageList,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    },
    message: '获取收藏物资列表成功'
  }
}

// 生成物资报表数据
function getMaterialReport(config) {
  const { startDate, endDate } = param2Obj(config.url)
  
  // 生成报表模拟数据
  return {
    code: 200,
    data: {
      statistics: {
        totalInbound: Random.integer(500, 2000),
        totalOutbound: Random.integer(300, 1500),
        totalTypes: Random.integer(30, 100),
        activeUsers: Random.integer(10, 50)
      },
      rankings: {
        inbound: [
          { name: '口罩', value: Random.integer(100, 500) },
          { name: '消毒液', value: Random.integer(80, 300) },
          { name: '手套', value: Random.integer(50, 200) },
          { name: '药品', value: Random.integer(40, 150) },
          { name: '防护服', value: Random.integer(30, 120) }
        ],
        outbound: [
          { name: '口罩', value: Random.integer(90, 400) },
          { name: '消毒液', value: Random.integer(70, 250) },
          { name: '手套', value: Random.integer(40, 180) },
          { name: '药品', value: Random.integer(30, 130) },
          { name: '防护服', value: Random.integer(20, 100) }
        ]
      },
      trend: {
        dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
        inbound: [120, 132, 101, 134, 90, 180],
        outbound: [90, 110, 90, 120, 80, 160]
      },
      category: [
        { name: '办公用品', value: 35 },
        { name: '电子设备', value: 20 },
        { name: '医疗用品', value: 25 },
        { name: '清洁用品', value: 10 },
        { name: '其他', value: 10 }
      ]
    },
    message: '获取报表数据成功'
  }
}

export default {
  getMaterials,
  getMaterialDetail,
  getMaterialCategories,
  applyMaterial,
  toggleFavoriteMaterial,
  getRelatedMaterials,
  getMaterialApplyRecords,
  getFavoriteMaterials,
  getMaterialReport
} 